//
//  MonitorViewController.m
//  IBaby
//
//  Created by ZengYuan on 14/11/21.
//  Copyright (c) 2014年 com.zhongwei. All rights reserved.
//

#import "MonitorViewController.h"
//#import "BabyInfo.h"
#import "MeViewController.h"

#import "AppDelegate.h"
#import "UserUnit.h"
#import "HomeViewController.h"
#include "cnplayer.h"
//#import "MLNavigationController.h"

#import "MonitorListViewController.h"
#import <AssetsLibrary/AssetsLibrary.h>
//#import "SHLineGraphView.h"
//#import "SHPlot.h"
#import "Config.h"


#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_8_0
#import <Photos/Photos.h>

#endif

//static NSString * const albumName = @"aiwebaby";

#define VIDEOSOURCE_COLOR  [UIColor colorWithRed:0.18 green:0.36 blue:0.41 alpha:1]

#define CLIENTSOURCE_COLOR  RGB(255, 87, 87)

#define BOTTOMBTNMARGIN 60//底部抓拍等按钮的间距
#define BOTTOMBTNHEIGHT 50//底部抓拍等按钮高度


@interface MonitorViewController ()
{
    
    //    VMediaPlayer       *mMPayer;
    CCnPlayer          *cawPlayer;
    BOOL                m_bConnected;
    NSTimer            *cawTimer;
    
    int                 timeFreshFailCount; //刷新失败次数
    
    UIPinchGestureRecognizer *pinch;
    UIPanGestureRecognizer   *pan;
    UITapGestureRecognizer *singleTap;
    UITapGestureRecognizer   *doubleTap;
    
    CGPoint              formerPoint;
    CGPoint              initialCenterPoint;
    
    CGFloat              initialWaitErrorViewX;
    //    CGPoint              changeFormerPoint;
    int changeDirection;
    
    char *alldata;
    char *yData;
    char *uData;
    char *vData;
    
    NSDate *serverCurrentDate;
    
    NSTimeInterval remainWatchTimeInterval;//本时间段内剩余观看时长
    
    PLAYER_HANDLE awplayer_handle;
    
//    SHLineGraphView *_lineGraph;
    
    NSMutableArray *deviceRatesArray;
    NSMutableArray *clientRatesArray;
    
    
    NSMutableArray *plot1ValuesArray;
    NSMutableArray *plot2ValuesArray;
    
    ALAssetsLibrary *assetsLibrary;
    
    BOOL transformManu;
}
@property (nonatomic,weak) UITapGestureRecognizer *longpressReg;
@end

@implementation MonitorViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    StandardPortraitScreenWidth = [[NSUserDefaults standardUserDefaults] floatForKey:@"Portrait_kScreenWidth"];
    StandardPortraitScreenHeight = [[NSUserDefaults standardUserDefaults] floatForKey:@"Portrait_kScreenHeight"];
    
    awplayer_handle=0;
    [self initBaseWork];
    
    //
    //    if (self.disabledPlayingStreamJustViewSee) {
    //        return;
    //    }
    //
    [self initCAWPlayer];
    [self addFullloadView];
    [fullloadingView showLoadingState];
    
    [self setupObservers];
    
    serverCurrentDate = [[NSDate date] dateByAddingTimeInterval:self.servertinterval];
    
    //    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    //    [formatter setDateFormat : @"yyyy-MM-dd HH:mm:ss"];
    //    NSTimeZone *localTimeZone = [NSTimeZone localTimeZone];
    //    [formatter setTimeZone:localTimeZone];
    //    NSLog(@"date = %@", [formatter stringFromDate:serverCurrentDate]);
    
    //符合播放时段
    BOOL ok = [self compareDateVideoWatch];
    if (ok) {
        
        currentSelectedDevice = self.devicesArray[self.currentDeviceIndex];
        if (currentSelectedDevice) {
            [self dismissFullloadingView];
            
//            deviceNameLabel.text = currentSelectedDevice.device_channel_name;
            self.titleLabel.text = currentSelectedDevice.device_channel_name;

            
            //add gesture
            [self addGesture];
            //add reach
            [self addReachabilityChangedNotifi];
            //开始定时
            
            [self performSelector:@selector(videoWatchTimeOut) withObject:nil afterDelay:remainWatchTimeInterval];
            
        }
        
    }else{
        [fullloadingView showErrorMsg:@"视频此时段暂时不提供播放"];
    }
}

-(void)initBaseWork{
    
    carrierView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.width*(3/4.0))];
    carrierView.backgroundColor=RGB(0, 0, 0);
    [self.view addSubview:carrierView];
    carrierView.clipsToBounds=YES;
    
    carrierWidth = carrierView.frame.size.width;
    
    portraitView = [[UIView alloc]initWithFrame:CGRectMake(0, carrierView.frame.size.height, self.view.frame.size.width, self.view.frame.size.height - carrierView.frame.size.height - self.navigationController.navigationBar.frame.size.height -(OSVersionIsAtLeastiOS7?20:0))];
    [self.view insertSubview:portraitView belowSubview:carrierView];
    portraitView.backgroundColor=[UIColor whiteColor];
    
    float labelY = (portraitView.bounds.size.height - 150)/2;
    
//    deviceNameLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, labelY, portraitView.frame.size.width, 30)];
//    deviceNameLabel.textAlignment = NSTextAlignmentCenter;
//    deviceNameLabel.font = [UIFont systemFontOfSize:24];
//    deviceNameLabel.textColor = RGB(82, 82, 82);
//    [portraitView addSubview:deviceNameLabel];
    
    //    CGFloat btnW = 60;
//    CGFloat btnmargin = (portraitView.frame.size.width - 2 * BOTTOMBTNHEIGHT) / 4;
    float btnY = 60;
    // float intervalX =  (portraitView.bounds.size.width - 66*2 - 38)/2;
    scaleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [scaleBtn setFrame:CGRectMake(carrierView.bounds.size.width - 45, carrierView.bounds.size.height - 45, 40, 40)];
    [carrierView addSubview:scaleBtn];
    [scaleBtn setBackgroundImage:[UIImage imageNamed:@"fallscreen"] forState:UIControlStateNormal];
//    [scaleBtn setBackgroundImage:[UIImage imageNamed:@"fallscreen_h"] forState:UIControlStateHighlighted];
    [scaleBtn addTarget:self action:@selector(transformManul:) forControlEvents:UIControlEventTouchUpInside];
    
    scaleBtn.autoresizingMask =   UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleTopMargin;
    
    
//    scaleBtn.layer.masksToBounds = YES;
//    scaleBtn.layer.cornerRadius = scaleBtn.frame.size.width / 2;
    
    
    captureBtn = [[YellowTitleBtn alloc] init];
    [captureBtn setFrame:CGRectMake((portraitView.frame.size.width - 66)/2, btnY, 66, 71)];
    [captureBtn setImage:[UIImage imageNamed:@"capture"] forState:UIControlStateNormal];
    [captureBtn setImage:[UIImage imageNamed:@"capture_h"] forState:UIControlStateHighlighted];
    [portraitView addSubview:captureBtn];
    [captureBtn addTitle:@"图像抓拍"];
    [captureBtn addTarget:self action:@selector(capture:) forControlEvents:UIControlEventTouchUpInside];
//    captureBtn.layer.masksToBounds = YES;
//    captureBtn.layer.cornerRadius = captureBtn.frame.size.width / 2;
    
    //暂停\继续播放按钮
//    pauseBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    [pauseBtn addTarget:self action:@selector(clickPause) forControlEvents:UIControlEventTouchUpInside];
//    pauseBtn.userInteractionEnabled = YES;
//    pauseBtn.frame = CGRectMake(0, carrierView.frame.size.height - 44, 60, 44);
//    [pauseBtn setImage:[UIImage imageNamed:@"pausebtn"] forState:UIControlStateNormal];
//    [pauseBtn setImage:[UIImage imageNamed:@"pausebtn_s"] forState:UIControlStateSelected];
//    [self.view addSubview:pauseBtn];
    
    //    pauseBtn.enabled = NO;
}


-(void)makeScaleBtnUpper{
    [carrierView bringSubviewToFront:scaleBtn];
}

-(void)pauseTimer:(BOOL)pause{
    if (pause) {
        
        if (cawTimer) {
            [cawTimer invalidate];
            cawTimer = nil;
        }
        
        [self freeData];
    }else{
        
        [self initData];
        
        cawTimer = [NSTimer scheduledTimerWithTimeInterval:0.03 target:self
                                                  selector:@selector(timeFresh:) userInfo:currentSelectedDevice repeats:YES];
        [[NSRunLoop mainRunLoop] addTimer:cawTimer forMode:NSRunLoopCommonModes];
    }
    
}

//暂停与继续播放
- (void)clickPause{
    
    pauseBtn.selected = !pauseBtn.selected;
    [self pauseTimer:pauseBtn.selected];
    
}


-(void)setNavbarItem{
    [super setNavbarItem];
    self.titleLabel.text=@"实时视频";
    self.backBtnPar.hidden=NO;
    
    //当前有全屏警告框，隐藏rate view
    //    if (fullloadingView) {
    //        return;
    //    }
    //
//    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"RateView" owner:self options:nil];
//    rateView = nib[0];
//    [self.view addSubview:rateView];
//    rateView.backgroundColor=[UIColor clearColor];
//    rateView.frame = CGRectMake(self.view.frame.size.width-65, 10, 59, 23);
//    
//    [self.navigationController.navigationBar addSubview:rateView];
//    
//    //    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:rateView];
//    
//    UITapGestureRecognizer *longpressReg = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(showHidePlotView)];
//    [rateView addGestureRecognizer:longpressReg];
//    self.longpressReg = longpressReg;
//    
    
}
//横屏
-(void)addLandscapeView{
    
    //landscapeBottomView
    if(!landscapeBottomView){
        
        //状态栏旋转到横屏的条件下
        float v = (StandardPortraitScreenWidth == 375 ? 1:(StandardPortraitScreenWidth < 375?(StandardPortraitScreenWidth+15)/375:(StandardPortraitScreenWidth-15)/375));
        float ViewHeight = 60*v;
        float ButtonWidth = 67;
        float ButtonHeight = 50;
        
        
        landscapeBottomView = [[UIView alloc]initWithFrame:CGRectMake(0, carrierView.frame.size.height, carrierView.frame.size.width, ViewHeight)];
        [carrierView addSubview:landscapeBottomView];
        [landscapeBottomView setBackgroundColor:RGBA(255, 255, 255, 0.5)];
        landscapeBottomView.userInteractionEnabled=YES;
        landscapeBottomView.autoresizingMask=UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleWidth;
        
        
//        float interval = (landscapeBottomView.frame.size.width - 160)/2;
        //landscape_scaleBtn
        landscape_scaleBtn =[UIButton buttonWithType:UIButtonTypeCustom];
        [landscape_scaleBtn setFrame:CGRectMake(landscapeBottomView.frame.size.width - 60, 5, 45, 45)];
        [landscape_scaleBtn setBackgroundImage :[UIImage imageNamed:@"normalscreen"] forState:UIControlStateNormal];
//        [landscape_scaleBtn setBackgroundImage:[UIImage imageNamed:@"normalscreen_h"] forState:UIControlStateHighlighted];
        
        [landscapeBottomView addSubview:landscape_scaleBtn];
        [landscape_scaleBtn addTarget:self action:@selector(transformManul:) forControlEvents:UIControlEventTouchUpInside];
//        landscape_scaleBtn.layer.masksToBounds = YES;
//        landscape_scaleBtn.layer.cornerRadius = landscape_scaleBtn.frame.size.width / 2;
        
        //landscape_captureBtn
        landscape_captureBtn =[UIButton buttonWithType:UIButtonTypeCustom];
        [landscape_captureBtn setFrame:CGRectMake((landscapeBottomView.frame.size.width - ButtonWidth)/2, (landscapeBottomView.frame.size.height - ButtonHeight)/2, ButtonWidth, ButtonHeight)];
        [landscape_captureBtn setBackgroundImage:[UIImage imageNamed:@"capture"] forState:UIControlStateNormal];
        [landscape_captureBtn setBackgroundImage:[UIImage imageNamed:@"capture_h"] forState:UIControlStateHighlighted];
        [landscapeBottomView addSubview:landscape_captureBtn];
        
        //        landscape_captureBtn.autoresizingMask=UIViewAutoresizingFlexibleLeftMargin;
        [landscape_captureBtn addTarget:self action:@selector(capture:) forControlEvents:UIControlEventTouchUpInside];
        
//        landscape_scaleBtn.layer.masksToBounds = YES;
//        landscape_scaleBtn.layer.cornerRadius = landscape_scaleBtn.frame.size.width / 2;
        //
    }
}

-(void)removeLandscapeView{
    if (landscapeBottomView) {
        [landscape_scaleBtn removeFromSuperview];
        landscape_scaleBtn = nil;
        
        [landscape_captureBtn removeFromSuperview];
        landscape_captureBtn = nil;
        
        [landscapeBottomView removeFromSuperview];
        landscapeBottomView=nil;
    }
}

#pragma mark LandscapeTopView

/*
 显示或者隐藏topview
 */

-(void)addLandscapeTopView{
    if(!landscapeTopView){
        
        //状态栏旋转到横屏的条件下， kScreenHeight为320（iphone5s）
        float v = (StandardPortraitScreenWidth == 375 ? 1:(StandardPortraitScreenWidth < 375?(StandardPortraitScreenWidth+15)/375:(StandardPortraitScreenWidth-15)/375));
        
        float YoffSet=(OSVersionIsAtLeastiOS7?20:0);
        float ViewHeight = 44*v + YoffSet;
        
        landscapeTopView = [[UIView alloc]initWithFrame:CGRectMake(0, -ViewHeight, carrierView.frame.size.width, ViewHeight)];
        [carrierView addSubview:landscapeTopView];
        landscapeTopView.backgroundColor =  RGBA(255, 165, 0,0.7);
        
        UILabel* landscapeTopLabel = [[UILabel alloc]initWithFrame:CGRectMake((landscapeTopView.frame.size.width-150)/2, YoffSet, 150, landscapeTopView.frame.size.height-YoffSet)];
        landscapeTopLabel.font =[UIFont systemFontOfSize:22];
        landscapeTopLabel.textColor=[UIColor whiteColor];
        landscapeTopLabel.backgroundColor=[UIColor clearColor];
        landscapeTopLabel.text=self.titleLabel.text;
        landscapeTopLabel.textAlignment=NSTextAlignmentCenter;
        [landscapeTopView addSubview:landscapeTopLabel];
        
        
        //right button
        UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        
        float rightBtnHeight = landscapeTopView.frame.size.height-YoffSet;
        [rightBtn setFrame:CGRectMake(landscapeTopView.bounds.size.width - rightBtnHeight-15, YoffSet, rightBtnHeight, rightBtnHeight)];
        [rightBtn addTarget:self action:@selector(showHideDevicesListView) forControlEvents:UIControlEventTouchUpInside];
        [landscapeTopView addSubview:rightBtn];
        [rightBtn setImage:[UIImage imageNamed:@"icon-列表选中"] forState:UIControlStateHighlighted];
        [rightBtn setImage:[UIImage imageNamed:@"icon-列表默认"] forState:UIControlStateNormal];
        
        
        //left back btn
        UIButton *leftBtn =[UIButton buttonWithType:UIButtonTypeCustom];
        [leftBtn setFrame:CGRectMake(15, YoffSet, landscapeTopView.frame.size.height, landscapeTopView.frame.size.height-YoffSet)];
        [leftBtn setImage:[UIImage imageNamed:@"common_backbtn"] forState:UIControlStateNormal];
        [leftBtn setImage:[UIImage imageNamed:@"common_backbtn_h"] forState:UIControlStateHighlighted];
        [landscapeTopView addSubview:leftBtn];
        [leftBtn addTarget:self action:@selector(transformManul:) forControlEvents:UIControlEventTouchUpInside];
        
        
        [self makeScaleBtnUpper];
    }
    
    
}

-(void)removeLandscapeTopView{
    if (landscapeTopView) {
        [landscapeTopView removeFromSuperview];
        landscapeTopView=nil;
    }
}

-(void)showLandscapeTopView{
    CGRect rect=landscapeTopView.frame;
    if (landscapeTopView.frame.origin.y<0) {
        rect.origin.y=0;
    }else{
        rect.origin.y=-landscapeTopView.frame.size.height;
    }
    
    [UIView animateWithDuration:0.2 animations:^{
        landscapeTopView.frame=rect;
    }];
}


-(BOOL)compareDateVideoWatch{
    
    NSDate *nowdate = [NSDate date];
    
    BOOL watchAvailable = [SystemUtils date:nowdate betweenDate:self.beginDate andDate:self.endDate];

    
    //当前时间段合适，不过还是要开启定时
    if (watchAvailable) {
        //test
//        temp = newEndstr;
        
        NSCalendar *cal = [NSCalendar currentCalendar];
        unsigned int unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
        
        NSDateComponents *d = [cal components:unitFlags fromDate:nowdate toDate:self.endDate options:0];
        remainWatchTimeInterval= [d hour]*3600+[d minute]*60+[d second];
        return YES;
    }

    
    return NO;
}

//-(BOOL)isBetweenDate:(NSDate*)beginDate andDate:(NSDate*)endDate
//{
//    if ([serverCurrentDate compare:beginDate] == NSOrderedAscending)
//        return NO;
//    if ([serverCurrentDate compare:endDate] == NSOrderedDescending)
//        return NO;
//    return YES;
//}


-(void)addGesture{
    pinch = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(handlePinch:)];
    [openglview addGestureRecognizer:pinch];
    
    pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
    pan.maximumNumberOfTouches=1;
    [openglview addGestureRecognizer:pan];
    
    singleTap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hideShowLandscapeView:)];
    singleTap.numberOfTapsRequired=1;
    singleTap.delegate=self;
    [carrierView addGestureRecognizer:singleTap];
    
    
    doubleTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleDoubleTap:)];
    doubleTap.numberOfTapsRequired = 2;
    [openglview addGestureRecognizer:doubleTap];
    
    [singleTap requireGestureRecognizerToFail:doubleTap];
    
}

-(void)removeGesture{
    [openglview removeGestureRecognizer:pinch];
    [openglview removeGestureRecognizer:pan];
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    if ([touch.view isDescendantOfView:devicesTableView]) {
        return NO;
    }
    
    return YES;
}


-(BOOL)initCAWPlayer{
    
    openglview = [[OpenGLView20 alloc]initWithFrame:carrierView.bounds];
    
    [carrierView addSubview:openglview];
    
    [self makeScaleBtnUpper];
    
    //申请足够的内存
    [self initData];
    
    leftLoadingFakeView = [[UIView alloc]initWithFrame:CGRectMake(-carrierView.frame.size.width, 0, carrierView.frame.size.width, carrierView.frame.size.height)
                           ];
    leftLoadingFakeView.backgroundColor=[UIColor blackColor];
    
    UILabel *nameLabel = [[UILabel alloc]initWithFrame:leftLoadingFakeView.bounds];
    nameLabel.autoresizingMask=UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
    [leftLoadingFakeView addSubview:nameLabel];
    nameLabel.textColor=[UIColor whiteColor];
    nameLabel.textAlignment =NSTextAlignmentCenter;
    nameLabel.backgroundColor=[UIColor clearColor];
    nameLabel.tag=100;
    
    [leftLoadingFakeView setBackgroundColor:carrierView.backgroundColor];
    [carrierView insertSubview:leftLoadingFakeView belowSubview:openglview];
    leftLoadingFakeOriginalX=leftLoadingFakeView.frame.origin.x;
    
    rightLoadingFakeView = [[UIView alloc]initWithFrame:CGRectMake(carrierView.frame.size.width, 0, carrierView.frame.size.width, carrierView.frame.size.height)
                            ];
    rightLoadingFakeView.backgroundColor=[UIColor blackColor];
    
    nameLabel = [[UILabel alloc]initWithFrame:rightLoadingFakeView.bounds];
    nameLabel.autoresizingMask=UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
    
    [rightLoadingFakeView addSubview:nameLabel];
    nameLabel.textColor=[UIColor whiteColor];
    nameLabel.backgroundColor=[UIColor clearColor];
    nameLabel.tag=100;
    nameLabel.textAlignment =NSTextAlignmentCenter;
    rightLoadingFakeOriginalX=rightLoadingFakeView.frame.origin.x;
    [carrierView insertSubview:rightLoadingFakeView belowSubview:openglview];
    
    
    [self freshFakeViewTitle];
    
    NSString *appversion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    UserUnit *user = [UserUnit getActiveUser];
    
    cawPlayer = CCnPlayer::Instance();
    BOOL ok = cawPlayer->Init([user.useruuid UTF8String], [appversion UTF8String]);
    return ok;
}

//-(void)addProgressView{
//    
//    progressView=[[ProgressView alloc]initWithFrame:CGRectMake(0, carrierView.bounds.size.height-5, carrierView.bounds.size.width, 5)];
//    progressView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleWidth;
//    [carrierView addSubview:progressView];
//}

-(BOOL)deviceRangeValid:(int)index{
    if (index <= self.devicesArray.count - 1 && index>=0) {
        return YES;
    }
    
    return NO;
}

-(void)freshFakeViewTitle{
    
    ChannelUnit *leftDeviceUnit=nil;
    ChannelUnit *rightDeviceUnit=nil;
    
    //最左侧
    if (self.currentDeviceIndex==0) {
        if ([self deviceRangeValid:self.currentDeviceIndex+1]) {
            rightDeviceUnit = [self.devicesArray objectAtIndex:self.currentDeviceIndex+1];
        }
        
    }
    
    //最右侧
    else if (self.currentDeviceIndex==self.devicesArray.count-1) {
        if ([self deviceRangeValid:self.currentDeviceIndex-1]) {
            leftDeviceUnit = [self.devicesArray objectAtIndex:self.currentDeviceIndex-1];
        }
    }else {
        
        if ([self deviceRangeValid:self.currentDeviceIndex+1]) {
            
            rightDeviceUnit = [self.devicesArray objectAtIndex:self.currentDeviceIndex+1];
        }
        
        if ([self deviceRangeValid:self.currentDeviceIndex-1]) {
            leftDeviceUnit = [self.devicesArray objectAtIndex:self.currentDeviceIndex-1];
        }
        
    }
    
    
    if (rightDeviceUnit) {
        UILabel *nameLabel =(UILabel *)[rightLoadingFakeView viewWithTag:100];
        nameLabel.text=[NSString stringWithFormat:@"连接%@",rightDeviceUnit.device_channel_name];
        ;
    }
    
    
    if (leftDeviceUnit) {
        UILabel *nameLabel =(UILabel *)[leftLoadingFakeView viewWithTag:100];
        nameLabel.text=[NSString stringWithFormat:@"连接%@",leftDeviceUnit.device_channel_name];
    }
}

-(void)restoreFakeView{
    
    CGRect rec = leftLoadingFakeView.frame;
    rec.origin.x=-openglview.frame.size.width;
    rec.origin.y=0;
    rec.size.width=openglview.frame.size.width;
    rec.size.height=openglview.frame.size.height;
    leftLoadingFakeView.frame=rec;
    
    leftLoadingFakeOriginalX=rec.origin.x;
    
    
    rec = rightLoadingFakeView.frame;
    rec.origin.x=openglview.frame.size.width;
    rec.origin.y=0;
    rec.size.width=openglview.frame.size.width;
    rec.size.height=openglview.frame.size.height;
    rightLoadingFakeView.frame=rec;
    
    rightLoadingFakeOriginalX=rec.origin.x;
    
}

-(void)startCAWPlaying:(NSString *)url{
    //    data =(char *)malloc(5*1024*1024);
    
    if (awplayer_handle>0 || cawPlayer==NULL) {
        return;
    }
    
    awplayer_handle = cawPlayer->Connect(url.UTF8String);
    NSLog(@"startCAWPlaying===＝＝＝===== %d",awplayer_handle);
    
    cawTimer = [NSTimer scheduledTimerWithTimeInterval:0.03 target:self
                                              selector:@selector(timeFresh:) userInfo:currentSelectedDevice repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:cawTimer forMode:NSRunLoopCommonModes];
    
}

-(void)timeFresh:(NSTimer *)atimer{
    
    //关闭定时器，断开连接
    DeviceUnit *deviceunit = atimer.userInfo;
//    if (!deviceunit.allowConnecting) {
//        [cawTimer invalidate];
//        cawTimer = nil;
//        return;
//    }else{
//    }
    
    if(!m_bConnected)
    {
        int tag =cawPlayer->GetConnectResult(awplayer_handle);
        NSString *reason=nil;
        
        switch(tag)
        {
            case 0:
                timeFreshFailCount=0;
                m_bConnected=YES;
                break;
                
            case 1:
                //连接失败
                timeFreshFailCount++;
                m_bConnected = NO;
                reason=@"视频连接失败";
                break;
                
            case 2:
                //连接断开
                timeFreshFailCount++;
                m_bConnected = NO;
                reason=@"视频连接断开";
                break;
                
            case 3:
                //正在连接中
                m_bConnected = NO;
                break;
                
            case 4:
                //未发动连接
                m_bConnected = NO;
                break;
            default:
                break;
        }
        
        
        if(!m_bConnected){
            
            if(timeFreshFailCount >= 300){
                [self streamError:nil];
            }
            
            return;
        }
    }
    
    
    
    int len=5*1024*1024;
    int yLen;
    int uLen;
    int vLen;
    
    long w;
    long h;
    int yStride;
    int uvStride;
    int errcode;
    
    float deviceFlowRate;
    float clientFlowRate;
    
    BOOL ok=NO;
    @try {
        
        DeviceUnit *deviceunit = atimer.userInfo;
        if (1) {
            
            if(alldata!=NULL){
                ok = cawPlayer->GetMediaData(awplayer_handle, alldata, len, yLen, uLen, vLen,w,h, yStride,uvStride, errcode,deviceFlowRate, clientFlowRate);
            }else{
                return;
            }
            //            NSLog(@"deviceFlowRate=%.2f clientFlowRate=%.2f", deviceFlowRate, clientFlowRate);
        }
    }
    @catch (NSException *exception) {
        //        NSLog(@"exception = %@", exception);
        [self performSelectorOnMainThread:@selector(streamError:) withObject:nil waitUntilDone:NO];
        return;
    }
    @finally {
        
    }
    
    //正常
    if(errcode == 0){
        if (ok){
            currentSuccessVideoFrame = YES;
            
            //更新
//            [rateView updateDeviceRate:deviceFlowRate ClientRate:clientFlowRate];
            //prepare
            if (!plot1ValuesArray) {
                plot1ValuesArray=[NSMutableArray array];
                for(int i=0;i<12;i++){
                    [plot1ValuesArray addObject:@(0.0)];
                }
                
            }
            
            if (!plot2ValuesArray) {
                plot2ValuesArray=[NSMutableArray array];
                for(int i=0;i<12;i++){
                    [plot2ValuesArray addObject:@(0.0)];
                }
                
            }
            
            BOOL deviceRateOkInTime=NO;
            // add new device rate
            if(deviceFlowRate>=0.0 && deviceFlowRate <= 1.0){
                [plot1ValuesArray addObject:@(deviceFlowRate)];
                deviceRateOkInTime=YES;
            }
            if (plot1ValuesArray.count>12) {
                [plot1ValuesArray removeObjectAtIndex:0];
            }
            
            
            // add new client rate
            BOOL clientRateOkInTime=NO;
            if(clientFlowRate>=0.0 && clientFlowRate <= 1.0){
                [plot2ValuesArray addObject:@(clientFlowRate)];
                clientRateOkInTime=YES;
                
            }
            // add new client rate
            if (plot2ValuesArray.count>12) {
                [plot2ValuesArray removeObjectAtIndex:0];
            }
            
//            //fresh rate
//            if (_lineGraph &&
//                plot1ValuesArray.count==12&&plot2ValuesArray.count==12 &&
//                clientRateOkInTime && deviceRateOkInTime){
//                [self refreshPlots];
//            }
//            
            
            
            timeFreshFailCount=0;
            if ([NSThread isMainThread]) {
                [self dismissLoadingErrorWindowMainThread];
            }else{
                [self performSelectorOnMainThread:@selector(dismissLoadingErrorWindowMainThread) withObject:nil waitUntilDone:YES];
            }
            
            if (w==yStride) {
                if (alldata!=NULL) {
                    [openglview displayYUV420pData:alldata width:w height:h];
                }
                
            }else{
                
                if (alldata!=NULL) {
                    
                    for (int i=0; i<h; i++) {
                        
                        memcpy(yData+i*w, alldata + i * yStride, w);
                        if(i < h / 2){
                            memcpy(uData+i*(w/2), alldata + yLen + i * uvStride, w / 2);
                            memcpy(vData+i*(w/2), alldata + yLen + uLen + i * uvStride, w / 2);
                        }
                    }
                    
                    [openglview displayYUV420pData:alldata width:w height:h imageBufferY:yData imageBufferU:uData imageBufferV:vData];
                }
                
            }
            
        }
        else{
//            currentSuccessVideoFrame=NO;
            
            timeFreshFailCount++;
            
            if (timeFreshFailCount == 20) {
                if ([NSThread isMainThread]) {
                    [self showLoadingView];
                }else{
                    [self performSelectorOnMainThread:@selector(showLoadingView) withObject:nil waitUntilDone:NO];
                }
            }else if(timeFreshFailCount >= 300){
                if ([NSThread isMainThread]) {
                    //                NSLog(@"isMainThread ========");
                    [self streamError:nil];
                }else{
                    //                NSLog(@"not isMainThread ========");
                    
                    [self performSelectorOnMainThread:@selector(streamError:) withObject:nil waitUntilDone:NO];
                }
                
            }
            
            //            NSLog(@"GetMediaData fail");
        }
    }
    else{
        currentSuccessVideoFrame=NO;
        //视频连接断开或内存分配不足
        
        if ([NSThread isMainThread]) {
            [self streamError:@"视频连接断开"];
        }else{
            [self performSelectorOnMainThread:@selector(streamError:) withObject:
             @"视频连接断开" waitUntilDone:NO];
        }
        
    }
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
//    if ([self.navigationController respondsToSelector:@selector(removeNavPanGesture)]) {
//        [(MLNavigationController *)(self.navigationController) removeNavPanGesture];
//    }
//    
    
    //    DeviceUnit *device = self.devicesArray[self.currentDeviceIndex];
    
    //    self.titleLabel.text = device.name;
    self.titleLabel.text = @"实时视频";
}


-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIDeviceOrientationDidChangeNotification object:nil];
    
    if (cawTimer) {
        [cawTimer invalidate];
        cawTimer=nil;
    }
    
    [self releaseGraphView];
    
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(videoWatchTimeOut) object:nil];
}

-(void)hideShowLandscapeView:(UITapGestureRecognizer*)reg{
    
    //devicesListCoverView存在，先删除
    if (devicesListCoverView) {
        [self showHideDevicesListView];
    }else{
        if([self currentScreenLandscape]){
            //hide show landscape bottom view
            CGRect frame = landscapeBottomView.frame;
            
            if (frame.origin.y == carrierView.frame.size.height  - frame.size.height) {
                //隐藏
                [UIView animateWithDuration:0.2 animations:^{
                    CGRect rect= landscapeBottomView.frame;
                    rect.origin.y = carrierView.frame.size.height;
                    landscapeBottomView.frame=rect;
                    
                    CGRect pauseBtnFrame = pauseBtn.frame;
                    pauseBtnFrame.origin.y = carrierView.frame.size.height;
                    pauseBtn.frame=pauseBtnFrame;
                    
                }];
                
                [[UIApplication sharedApplication] setStatusBarHidden:YES];
                
            }else{
                //显示
                [UIView animateWithDuration:0.2 animations:^{
                    CGRect rect= landscapeBottomView.frame;
                    rect.origin.y = carrierView.frame.size.height  - rect.size.height;
                    landscapeBottomView.frame=rect;
                    
                    CGRect pauseBtnFrame = pauseBtn.frame;
                    pauseBtnFrame.origin.y = carrierView.frame.size.height - pauseBtnFrame.size.height;
                    pauseBtn.frame=pauseBtnFrame;
                    
                }];
                
                [[UIApplication sharedApplication] setStatusBarHidden:NO];
            }
            
            //hide show landscape top view
            [self showLandscapeTopView];
        }
        
    }
    
    
    
    
}

#pragma mark - loadingview

-(void)showLoadingView{
    
    if (!waitview) {
        waitview = [[WaitView alloc]initWithFrame:CGRectMake(0, 0, 100, 63)];
        [carrierView addSubview:waitview];
        
    }
    pauseBtn.enabled = NO;
    waitview.center = CGPointMake(carrierView.bounds.size.width/2, carrierView.bounds.size.height/2);
    waitview.backgroundColor=[UIColor clearColor];
    waitview.autoresizingMask = UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleBottomMargin|UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin;
    [waitview startRoll];
}

-(void)dismissLoadingView{
    
    if(waitview){
        [waitview stopRoll];
        [waitview removeFromSuperview];
        waitview=nil;
    }
    pauseBtn.enabled = YES;
}

//-(void)

-(void)showErrorView:(NSString *)error{
    if (!errorview) {
        errorview = [[ErrorView alloc]initWithFrame:CGRectMake(0, 0, 20, 29) text:error];
        [carrierView addSubview:errorview];
    }
    
    errorview.center = CGPointMake(carrierView.bounds.size.width/2, carrierView.bounds.size.height/2);
    errorview.backgroundColor=[UIColor clearColor];
    errorview.autoresizingMask = UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleBottomMargin|UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin;
}

-(void)showErrorViewAllowTapresume:(NSString *)error{
    [self showErrorView:error];
    
    if (!resumePlayingTapBtn) {
        resumePlayingTapBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [resumePlayingTapBtn setFrame:carrierView.bounds];
        [carrierView addSubview:resumePlayingTapBtn];
        [resumePlayingTapBtn addTarget:self action:@selector(resumePlayingTapReg:) forControlEvents:UIControlEventTouchUpInside];
        
        [self makeScaleBtnUpper];
    }
    
}

-(void)dismissErrorView{
    if(errorview){
        [errorview removeFromSuperview];
        errorview=nil;
    }
    if(resumePlayingTapBtn){
        [resumePlayingTapBtn removeFromSuperview];
        resumePlayingTapBtn = nil;
        
    }
}

-(void)showNewworkErrorView{
    if (!bannerview) {
        bannerview=[[BannerView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 50)];
        [self.view addSubview:bannerview];
        bannerview.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    }
}

-(void)dismissNewworkErrorView{
    if(bannerview){
        [bannerview removeFromSuperview];
        bannerview=nil;
    }
}

-(void)dismissLoadingErrorWindowMainThread{
    [self dismissErrorView];
    [self dismissLoadingView];
}
#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (alertView.tag == 300) {
        ensureAskAlertShowing=NO;
        
        if (buttonIndex==0) {
            [self quicklyStopMovie];
            [self clearCurVideoPic];

            [self dismissLoadingView];
            
            [self showErrorViewAllowTapresume:@"播放停止，单击继续播放"];
            
        }else{
            //允许用户这次再3G状态下进行视频播放
            
            
            g_allowUserPlayVideoIn3G=YES;
            [self startPreparePlaying];
        }
    }else if (alertView.tag == 400) {
        [self navLeftAction];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setupObservers
{
    NSNotificationCenter *def = [NSNotificationCenter defaultCenter];
    [def addObserver:self
            selector:@selector(applicationDidEnterForeground:)
                name:UIApplicationDidBecomeActiveNotification
              object:[UIApplication sharedApplication]];
    [def addObserver:self
            selector:@selector(applicationDidEnterBackground:)
                name:UIApplicationWillResignActiveNotification
              object:[UIApplication sharedApplication]];
}

- (void)unSetupObservers{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

//进入前台
- (void)applicationDidEnterForeground:(NSNotification *)notification
{
    DLog(@"DidEnterForeground******************");
    [self ensureBeforePreparePlaying];
}

//进入后台
- (void)applicationDidEnterBackground:(NSNotification *)notification
{
    DLog(@"DidEnterForeground******************");
    [self quicklyStopMovie];
}

-(void)changeStream:(DeviceUnit *)willPlayDeviceUnit{
    [self quicklyStopMovie];
    [self clearCurVideoPic];

    //restore opengl view frame normal
    float limitWidth;
    float limitHeight;
    //横屏
    if ([self currentScreenLandscape]) {
        limitWidth = StandardPortraitScreenHeight;
        limitHeight= StandardPortraitScreenWidth;
        
    } //竖屏
    else{
        limitWidth = carrierWidth;
        limitHeight= carrierView.frame.size.height;
    }
    
    //reset frame
    CGRect rec = openglview.frame;
    rec.origin.x=0;
    rec.origin.y=0;
    rec.size.width=limitWidth;
    rec.size.height=limitHeight;
    openglview.frame=rec;
    
    [self restoreFakeView];
    
    //reset device label
//    deviceNameLabel.text = willPlayDeviceUnit.device_channel_name;
    
    self.titleLabel.text = willPlayDeviceUnit.device_channel_name;
    
    //reset fake title
    [self freshFakeViewTitle];
    
    currentSelectedDevice=willPlayDeviceUnit;
//    currentSelectedDevice.allowConnecting=YES;
    [self ensureBeforePreparePlaying];
}

-(void)playStream:(NSString *)fileStream{
    timeFreshFailCount=0;
    [self startCAWPlaying:fileStream];
    
}

-(void)streamError:(NSString *)error{
    [self quicklyStopMovie];
    [self clearCurVideoPic];

    pauseBtn.enabled = NO;
    [self dismissLoadingView];
    [self showErrorViewAllowTapresume:error.length? error:@"视频连接失败"];
    //    [self showErrorView:error.length? error:@"视频连接失败"];
}

-(void)resumePlayingTapReg:(UIButton *)sender{
    
    [self startPreparePlaying];
}


-(void)quicklyStopMovie{
    
    currentSelectedDevice.allowConnecting=NO;
    
    if (cawPlayer) {
        [cawTimer invalidate];
        cawTimer = nil;
    }
    
    if(cawPlayer!=NULL){
        
        if(awplayer_handle>0){
            NSLog(@"Disconnect===＝＝＝===== %d",awplayer_handle);
            cawPlayer->Disconnect(awplayer_handle);
            awplayer_handle=0;
        }
        
        //清空显示界面, 注释具体原因参考苹果官方关于open gl的文档 --- zengyuan。
    }
    
}


- (NSString *)getCacheRootDirectory
{
    NSString *cache = [NSString stringWithFormat:@"%@/Library/Caches/MediasCaches", NSHomeDirectory()];
    if (![[NSFileManager defaultManager] fileExistsAtPath:cache]) {
        [[NSFileManager defaultManager] createDirectoryAtPath:cache
                                  withIntermediateDirectories:YES
                                                   attributes:nil
                                                        error:NULL];
    }
    return cache;
}


-(void)navLeftAction
{
    [self saveLastMonitorImage];
    [super navLeftAction];
}

- (void) initData{
    size_t size = 5*1024*1024;
    if (alldata == NULL) {
        alldata =(char *)malloc(size);
    }
    
    size = 3*1024*1024;
    if (yData == NULL) {
        yData = (char *)malloc(size);
    }
    
    size = 1*1024*1024;
    if (uData == NULL) {
        uData = (char *)malloc(size);
    }
    
    if (vData == NULL) {
        vData = (char *)malloc(size);
    }
}

-(void)freeData{
    if (alldata!=NULL) {
        free(alldata);
        alldata = NULL;
    }
    
    if (yData!=NULL) {
        free(yData);
        yData = NULL;
    }
    
    if (uData!=NULL) {
        free(uData);
        uData = NULL;
    }
    
    if (vData!=NULL) {
        free(vData);
        vData = NULL;
    }
}

-(void)destoryMemBeforePop{
    NSLog(@"destoryMemBeforePop");
    
    
    [self quicklyStopMovie];
    if (cawPlayer!=NULL) {
        cawPlayer=NULL;
    }
    [self unSetupObservers];
    [self freeData];
    
    [self resetOrientationPortrait];
}

/**
 *  清空当前视频画面
 */
-(void)clearCurVideoPic{
    //清空画面
    if([UIApplication sharedApplication].applicationState ==UIApplicationStateActive){
        [openglview clearFrame];
    }
}

- (void)dealloc
{
    NSLog(@"dealloc");
    [self destoryMemBeforePop];
}


-(NSArray*)sectionArray:(NSInteger)section{
    
    if (section * 3  >= classAreaArray.count || MIN(3, classAreaArray.count - section*3) > classAreaArray.count) {
        MBALERT(@"error sectionArray , lianxi zeng");
    }
    
    NSArray *subClassAreaArray = [[NSArray alloc]initWithArray:[classAreaArray subarrayWithRange:NSMakeRange(section*3, MIN(3, classAreaArray.count - section*3))]];
    return subClassAreaArray;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.devicesArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    float v = (StandardPortraitScreenWidth == 375 ? 1:(StandardPortraitScreenWidth < 375?(StandardPortraitScreenWidth+15)/375:(StandardPortraitScreenWidth-15)/375));
    return 50*v;
}

- (UITableViewCell *)tableView:(UITableView *)_tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *CellActivity = @"CellActivity";
    UITableViewCell *cell=[_tableView dequeueReusableCellWithIdentifier:CellActivity];
    if (!cell) {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellActivity];
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 150, cell.frame.size.height)];
        [cell.contentView addSubview:label];
        cell.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        cell.backgroundColor=RGBA(255, 255, 255, 0.5);
        label.textAlignment = NSTextAlignmentCenter;
        label.backgroundColor=[UIColor clearColor];
        label.tag=100;
        label.autoresizingMask = UIViewAutoresizingFlexibleHeight;
        
    }
    
    DeviceUnit *deviceunit = self.devicesArray[indexPath.row];
    UILabel *label = (UILabel *)[cell.contentView viewWithTag:100];
    label.text=deviceunit.device_channel_name;
    if (indexPath.row == self.currentDeviceIndex) {
        label.textColor=RGB(255, 87, 87);
    }else{
        label.textColor=RGB(82, 82, 82);
    }
    
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    DeviceUnit *willPlayDeviceUnit= [self.devicesArray objectAtIndex:indexPath.row];
    self.currentDeviceIndex=indexPath.row;
    [self showHideDevicesListView];
    [self changeStream:willPlayDeviceUnit];
}


/**
	* @brief 准备播放前进行网络询问
 
	*/

-(void)ensureBeforePreparePlaying{
    
    if (ensureAskAlertShowing) {
        return;
    }
    
    if (openedSectionIndex == -1) {
        return;
    }
    
    //    NSString *dname=currentSelectedDevice.name;
    //    if ([dname length]==0) {
    //        dname = [NSString stringWithFormat:@"摄像头%d",currentSelectedDevice.device_channel_no+1];
    //    }
    
    if ([networkReach isReachable]){
        if (![networkReach isReachableViaWiFi]){
            NSLog(@"reachabilityForLocalWiFi isnotreachable 3g, is  reachable");
            
            //3G 需要提醒
            if ([[NSUserDefaults standardUserDefaults] objectForKey:KSWITCH_NOWIFIALERT] && g_allowUserPlayVideoIn3G==NO){
                
                if (![NSThread isMainThread]) {
                    [self performSelectorOnMainThread:@selector(nowifiAlertMainThread) withObject:nil waitUntilDone:NO];
                }else{
                    [self nowifiAlertMainThread];
                }
                
                
            }
            //不需要提醒
            else{
                [self startPreparePlaying];
            }
            
            
        }else{
            NSLog(@"reachabilityForLocalWiFi isreachable");
            //wifi
            [self startPreparePlaying];
        }
    }else{
        pauseBtn.enabled = NO;
        [self showErrorView:@"网络不可用"];
        
    }
    
    
    
    
}

-(void)nowifiAlertMainThread{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"当前WIFI不可用，继续播放可能产生数据流量费用，是否继续？" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles: @"取消",@"继续播放", nil];
    alert.tag=300;
    [alert show];
    ensureAskAlertShowing=YES;
}

/**
	* @brief 开始缓冲准备播放 ，加载播放缓冲等待画面，去掉播放错误界面（有的话）
 
	*/
-(void)startPreparePlaying{
    
    
    if (awplayer_handle>0) {
        DLog(@"awplayer_handle !=0 ************ cannot play");
        return;
    }
    
    if([((ChannelUnit *)currentSelectedDevice).device_channel_url length]==0){
        pauseBtn.enabled = NO;
        [self showErrorView:@"视频暂时无法播放"];
        return;
    }
    
    [self dismissErrorView];
    [self showLoadingView];
    
//    NSString *temp=@"rtmp://192.168.10.241:21935/live/A578747423";
    if ([currentSelectedDevice isKindOfClass:[ChannelUnit class]]) {
        [self playStream:((ChannelUnit *)currentSelectedDevice).device_channel_url];
    }
    
}


#pragma  mark - 网络状态变化处理
-(void)reachabilityChanged:(NSNotification*)note{
    
    NSLog(@"reachabilityChanged ************************************");
    Reachability * reach = [note object];
    
    if (reach == networkReach) {
        //网络通了
        if([reach isReachable]){
            
            //没有上线、不是访客 允许上线
//            if(![[OnlineEngine sharedInstance] isOnline] &&
//               ![[UserUnit getActiveUser] isGuest]) {                AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
//                [delegate onlineDispatch];
//            }
//            
            [self dismissNewworkErrorView];
            if([reach isReachableViaWiFi]){
                
                //当前是wifi，继续播放
                [self ensureBeforePreparePlaying];
                NSLog(@"-------isReachable wifi");
                
            }else{
                //不是wifi，咨询
                NSLog(@"--******************----isReachable 2g/3g");
                [self ensureBeforePreparePlaying];
            }
            //
        }else{
            //断网了
//            if([[OnlineEngine sharedInstance] isOnline] &&
//               ![[UserUnit getActiveUser] isGuest]) {
//                [[OnlineEngine sharedInstance] offline];
//            }
            
            [self dismissLoadingView];
            pauseBtn.enabled = NO;
            [self showErrorView:@"网络不可用"];
            if (![self currentScreenLandscape]) {
                [self showNewworkErrorView];
            }
            NSLog(@"not reachable");
        }
    }
}

/*
 - (void)orientationChanged:(NSNotification*)noti {
 UIDeviceOrientation orientation = [UIDevice currentDevice].orientation;
 
 NSLog(@"orientationChanged");
 
 if (orientation == UIDeviceOrientationPortrait) {
 [self rotateView:UIInterfaceOrientationPortrait];
 }else if (orientation == UIDeviceOrientationLandscapeLeft){
 [self rotateView:UIInterfaceOrientationLandscapeRight];
 }
 else if (orientation == UIDeviceOrientationLandscapeRight){
 [self rotateView:UIInterfaceOrientationLandscapeLeft];
 }
 
 }
 */


-(void)rotateView:(UIInterfaceOrientation)orientation{
    //旋转到portrait方向
    
    int val = 0;
    
    if (orientation == UIInterfaceOrientationPortrait) {
        
        //竖屏状态
        if (![self currentScreenLandscape]) {
            return;
        };
        [self.navigationController setNavigationBarHidden:NO];
        
        carrierView.frame  = CGRectMake(0, 0, carrierWidth, carrierWidth*(3/4.0));
        openglview.frame=carrierView.bounds;
        [self restoreFakeView];
        [self removeLandscapeView];
        [self removeLandscapeTopView];
        
        val = UIInterfaceOrientationPortrait;
        pauseBtn.frame = CGRectMake(0, carrierView.frame.size.height - 44, 60, 44);
        
        scaleBtn.hidden= NO;
        
    }else{
        if ([self currentScreenLandscape]) {
            return;
        };
        
        //横屏状态

        [self.navigationController setNavigationBarHidden:YES];
        carrierView.frame = CGRectMake(0, 0, StandardPortraitScreenHeight, StandardPortraitScreenWidth);
        
        
        openglview.frame=carrierView.bounds;
        [self restoreFakeView];
        
        [self addLandscapeView];
        [self addLandscapeTopView];
        [self dismissNewworkErrorView];
        //        pauseBtn.frame = CGRectMake(0, carrierView.frame.size.height - 44, 60, 44);
        
        CGRect pauseBtnFrame = pauseBtn.frame;
        pauseBtnFrame.origin.y = carrierView.frame.size.height;
        pauseBtn.frame=pauseBtnFrame;
        
        val = orientation;
        
        scaleBtn.hidden= YES;

    }
    
    
    if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
        
        SEL selector = NSSelectorFromString(@"setOrientation:");
        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
        [invocation setSelector:selector];
        [invocation setTarget:[UIDevice currentDevice]];
        [invocation setArgument:&val atIndex:2];
        [invocation invoke];
    }
    
    if (orientation == UIInterfaceOrientationPortrait) {
        [[UIApplication sharedApplication] setStatusBarHidden:NO];
    }else{
        [[UIApplication sharedApplication] setStatusBarHidden:YES];
    }
}



-(void)transformManul:(id)sender{
    
    transformManu=YES;
    
    UIInterfaceOrientation val = UIInterfaceOrientationUnknown;
    
    if([self currentScreenLandscape]){
        val = UIInterfaceOrientationPortrait;
        
    }else{
        val = UIInterfaceOrientationLandscapeRight;
    }
    
    [self rotateView:val];
}


/*
 @brief 该界面消失时，如果当前播放状态为横屏，则返回到竖屏
 */

-(void)resetOrientationPortrait{
    if ([self currentScreenLandscape]) {
        [self rotateView:UIInterfaceOrientationPortrait];
    }
}

-(void)releasePlayer{
    [self quicklyStopMovie];
    [self unSetupObservers];
}

#pragma mark  -
#pragma mark GestureRecognizer

//调整视图的位置，防止上下左右四个边界超出
-(void)adjustLimitWidth:(float)limitwidth limitHeight:(float)limitheight{
    CGRect rect = openglview.frame;
    if (rect.origin.x>0 ) {
        
        [UIView animateWithDuration:0.2 animations:^{
            CGRect rec = openglview.frame;
            rec.origin.x=0;
            openglview.frame=rec;
        }];
    }
    
    if (rect.origin.y>0 ) {
        
        [UIView animateWithDuration:0.2 animations:^{
            CGRect rec = openglview.frame;
            rec.origin.y=0;
            openglview.frame=rec;
        }];
    }
    
    if (rect.origin.x + rect.size.width< limitwidth) {
        
        [UIView animateWithDuration:0.2 animations:^{
            CGRect rec = openglview.frame;
            rec.origin.x=limitwidth - rect.size.width;
            openglview.frame=rec;
        }];
    }
    
    if (rect.origin.y+ rect.size.height <  limitheight) {
        
        [UIView animateWithDuration:0.2 animations:^{
            CGRect rec = openglview.frame;
            rec.origin.y= limitheight - rect.size.height;
            openglview.frame=rec;
        }];
    }
    
}

/* 识别放大缩小 */
- (void)handlePinch:(UIPinchGestureRecognizer *)gestureRecognizer {
    
    //    static CGFloat changedScale=1.0;
    
    float limitWidth;
    float limitHeight;
    
    //横屏
    if ([self currentScreenLandscape]) {
        
        limitWidth = StandardPortraitScreenHeight;
        limitHeight= StandardPortraitScreenWidth;
    }//竖屏
    else{
        limitWidth = carrierWidth;
        limitHeight= carrierView.frame.size.height;
    }
    
    //    NSLog(@"openglview.frame.size.width=%.2f limitWidth=%.2f", openglview.frame.size.width, limitWidth);
    
    int int_openglW = (int)(openglview.frame.size.width);
    int int_limitWidth = (int)(limitWidth);
    
    //    NSLog(@"gestureRecognizer.state = %d",gestureRecognizer.state);
    
    if (gestureRecognizer.state == UIGestureRecognizerStateChanged) {
        
        if( int_openglW > int_limitWidth*3 && gestureRecognizer.scale > 1){
            return;
        }
        
        
        if(int_openglW < int_limitWidth && gestureRecognizer.scale < 1){
            return;
        }
        
        CGPoint location = [gestureRecognizer locationInView:self.view];
        
        
        //        changedScale = openglview.frame.size.width/limitWidth;
        //        NSLog(@"changedScale gestureRecognizer.scale = %.2f ", changedScale);
        NSLog(@"gestureRecognizer.view.frame.origin.x = %.2f", gestureRecognizer.view.frame.origin.x
              );
        
        gestureRecognizer.view.transform = CGAffineTransformScale(gestureRecognizer.view.transform, gestureRecognizer.scale, gestureRecognizer.scale);
        
        //手动处理下偏移
        
        CGPoint center = gestureRecognizer.view.center;
        float HOffset = 0;
        
        //处理视频水平方向偏移
        if(location.x> gestureRecognizer.view.center.x){
            HOffset = gestureRecognizer.scale;
        }else{
            HOffset = -gestureRecognizer.scale;
        }
        //        if ([self currentScreenLandscape]) {
        //            center.y += HOffset;
        //        }else{
        center.x += HOffset;
        //        }
        
        float VOffset = 0;
        //处理视频垂直方向偏移
        if(location.y> gestureRecognizer.view.center.y){
            VOffset = gestureRecognizer.scale;
        }else{
            VOffset = -gestureRecognizer.scale;
        }
        //        if ([self currentScreenLandscape]) {
        //            center.x += VOffset;
        //        }else{
        center.y += VOffset;
        //        }
        
        gestureRecognizer.view.center =center;
        gestureRecognizer.scale = 1;
        
    }
    
    
    
    else if (gestureRecognizer.state >= UIGestureRecognizerStateEnded) {
        
        //超过3倍
        if (int_openglW >= int_limitWidth*3) {
            
            [UIView animateWithDuration:0.2 animations:^{
                
                CGPoint point = openglview.center;
                CGRect rec = openglview.frame;
                
                rec.size.width=int_limitWidth*3;
                rec.size.height=limitHeight*3;
                openglview.frame=rec;
                
                openglview.center=point;
                
                
            }];
            
        }//小于1倍
        else if(int_openglW <= int_limitWidth){
            
            [UIView animateWithDuration:0.2 animations:^{
                CGRect rec = openglview.frame;
                rec.origin.x=0;
                rec.origin.y=0;
                rec.size.width=int_limitWidth;
                rec.size.height=limitHeight;
                openglview.frame=rec;
            }];
        }
        
        [self adjustLimitWidth:limitWidth limitHeight:limitHeight];
        
        //缩小，但比正常大0-50之间
        if(int_openglW >= int_limitWidth && int_openglW <= int_limitWidth+int_limitWidth/8 && gestureRecognizer.velocity<0){
            
            [UIView animateWithDuration:0.2 animations:^{
                CGRect rec = openglview.frame;
                rec.origin.x=0;
                rec.origin.y=0;
                rec.size.width=int_limitWidth;
                rec.size.height=limitHeight;
                openglview.frame=rec;
            }];
        }
        
        
        
        
    }
    
    
}

//当前屏幕状态是否横屏
-(BOOL)currentScreenLandscape{
    //横屏
    if (carrierView.frame.size.width == StandardPortraitScreenHeight) {
        return YES;
    }else{
        return NO;
    }
}

/* 识别拖动 */
- (void)handlePan:(UIPanGestureRecognizer *)gestureRecognizer {
    
    float limitWidth;
    float limitHeight;
    
    //横屏
    if ([self currentScreenLandscape]) {
        limitWidth = StandardPortraitScreenHeight;
        limitHeight= StandardPortraitScreenWidth;
        
    } //竖屏
    else{
        limitWidth = carrierWidth;
        limitHeight= carrierView.frame.size.height;
    }
    
    if(gestureRecognizer.state == UIGestureRecognizerStateBegan){
        CGPoint location = [gestureRecognizer locationInView:self.view];
        formerPoint= location;
        initialCenterPoint=openglview.center;
        
        //        changeFormerPoint = location;
        
        
        
    }else if(gestureRecognizer.state == UIGestureRecognizerStateChanged){
        
        CGPoint location = [gestureRecognizer locationInView:self.view];
        
        
        //正常状态下禁止拖动,允许切换视频
        if (openglview.frame.size.width >=  limitWidth-2 && openglview.frame.size.width <= limitWidth+2) {
            
            [self handlePanGestureChangeStream:gestureRecognizer];
            
            return;
        }
        
        float offsetX = location.x - formerPoint.x;
        float offsetY = location.y - formerPoint.y;
        openglview.center = CGPointMake(initialCenterPoint.x + offsetX, initialCenterPoint.y + offsetY);
        
        
    }else if(gestureRecognizer.state >= UIGestureRecognizerStateEnded){
        
        //正常状态下禁止拖动,允许切换视频
        if (openglview.frame.size.width >=  limitWidth-2 && openglview.frame.size.width <= limitWidth+2) {
            [self handlePanGestureChangeStream:gestureRecognizer];
            return;
        }
        
        [self adjustLimitWidth:limitWidth limitHeight:limitHeight];
    }
}


-(void)handleDoubleTap:(UITapGestureRecognizer *)tapGesture{
    NSLog(@"tap:******");
    
    
    float limitWidth;
    float limitHeight;
    
    
    //横屏
    if ([self currentScreenLandscape]) {
        limitWidth = StandardPortraitScreenHeight;
        limitHeight= StandardPortraitScreenWidth;
        
    } //竖屏
    else{
        limitWidth = carrierWidth;
        limitHeight= carrierView.frame.size.height;
    }
    
    
    int int_openglW = (int)(openglview.frame.size.width);
    int int_limitWidth = (int)(limitWidth);
    
    if (int_limitWidth == int_openglW) {
        NSLog(@"int equal");
    }
    
    if(openglview.frame.size.width==limitWidth){
        NSLog(@"float equal");
    }
    
    
    if( int_openglW > int_limitWidth){
        [self pauseTimer:YES];
        
        NSTimeInterval time =  0.2;
        [UIView animateWithDuration:time animations:^{
            CGRect rect = openglview.frame;
            rect.origin.x=0;
            rect.origin.y=0;
            rect.size.width=limitWidth;
            rect.size.height=limitHeight;
            openglview.frame=rect;
            
        } completion:^(BOOL finished) {
            [self pauseTimer:NO];
        }];
    }else{
        [self pauseTimer:YES];
        
        [UIView animateWithDuration:0.2 animations:^{
            
            CGRect rect    = openglview.frame;
            CGPoint center = openglview.center;
            
            rect.size.width=limitWidth*2;
            rect.size.height=limitHeight*2;
            openglview.frame=rect;
            openglview.center=center;
            
        }completion:^(BOOL finished) {
            [self pauseTimer:NO];
        }];
        
    }
    
    
}


#pragma mark  Save image

-(void)capture:(id)sender{
    
    //检查相册是否可用
    if (OSVersionIsAtLeastiOS7) {
        ALAuthorizationStatus authStatus = [ALAssetsLibrary authorizationStatus];
        if (authStatus == ALAuthorizationStatusDenied) {
            
            UIAlertView *alertView =[[UIAlertView alloc]initWithTitle:nil message:@"请前往系统设置->隐私->相片，开启爱维宝贝权限" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alertView show];
            return;
        }
        
        
        
    }
    
    
    UIImage*image = [openglview glToUIImage];
    [self saveCaptureImageToAiweiAlbum:image];
    
}

-(void)saveLastMonitorImage{
    if (errorview) {
        return;
    }
    
    if(fullloadingView){
        return;
    }
    
    if (!currentSuccessVideoFrame) {
        return;
    }
    
    if(cawPlayer==NULL){
        return;
    }
    
    NSFileManager*fileManager =[NSFileManager defaultManager];
    //    NSError*error;
    NSArray*paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString*documentsDirectory =[paths objectAtIndex:0];
    
    NSString*imagePath =[documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.jpg", currentSelectedDevice.device_channel_name]];
    if (![fileManager fileExistsAtPath:imagePath]) {
        UIImage*image = [openglview glToUIImage];
        
        NSData *imageData = UIImagePNGRepresentation(image);
        BOOL ok = [imageData writeToFile:imagePath atomically:YES];
        
        NSLog(@"saveLastMonitorImage ok..%d", ok);
    }
    
}



- (void)image:(UIImage *)image
didFinishSavingWithError:(NSError *)error
  contextInfo:(void *)contextInfo{
    if (!error) {
        //         MBALERT(@"图片已保存到相册");
        MBProgressHUD *ahud=[MBProgressHUD showHUDAddedTo:self.view animated:YES];
        ahud.userInteractionEnabled = NO;
        ahud.mode = MBProgressHUDModeText;
        ahud.labelText = @"图片已保存到相册";
        [ahud hide:YES afterDelay:0.7];
        
    }
    
}

-(void)videoWatchTimeOut{
    [self destoryMemBeforePop];
    
    //清空画面
    if([UIApplication sharedApplication].applicationState ==UIApplicationStateActive){
        [openglview clearFrame];
    }
    
    [self dismissLoadingErrorWindowMainThread];
    
    NSLog(@"videoWatchTimeOut");
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"抱歉，此时段视频播放已结束，请下一时段再观看" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定",nil];
    [alert show];
    alert.tag=400;
    
    
}


#pragma mark -  视频列表

/*
 -(void)addDevicesTable{
 if (!devicesTableView) {
 devicesTableView = [[UITableView alloc]initWithFrame:CGRectMake(carrierView.bounds.size.width-150, 50, 150, 200) style:UITableViewStylePlain];
 [carrierView addSubview:devicesTableView];
 devicesTableView.backgroundColor=[UIColor clearColor];
 devicesTableView.delegate=self;
 devicesTableView.dataSource=self;
 devicesTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
 }
 }*/

-(void)addDevicesListView{
    
    if (!devicesListCoverView) {
        devicesListCoverView = [[UIView alloc]initWithFrame:carrierView.bounds];
        [carrierView addSubview:devicesListCoverView];
        
        [devicesListCoverView setBackgroundColor:[UIColor clearColor]];
        //        devicesListCoverView.userInteractionEnabled=YES;
        
        UIButton *btn =[UIButton buttonWithType:UIButtonTypeCustom];
        [btn setFrame:devicesListCoverView.bounds];
        [devicesListCoverView addSubview:btn];
        [btn addTarget:self action:@selector(showHideDevicesListView) forControlEvents:UIControlEventTouchUpInside];
        
        devicesTableView = [[UITableView alloc]initWithFrame:CGRectMake(devicesListCoverView.bounds.size.width-150, landscapeTopView.frame.size.height, 150, 0) style:UITableViewStylePlain];
        [devicesListCoverView addSubview:devicesTableView];
        devicesTableView.backgroundColor=[UIColor clearColor];
        devicesTableView.delegate=self;
        devicesTableView.dataSource=self;
        devicesTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        
        //        UIImageView *arrowImgView =[[UIImageView alloc]initWithFrame:CGRectMake((devicesListCoverView.frame.size.width-50), 0, 19, 9)];
        //        [devicesListCoverView addSubview:arrowImgView];
        //        arrowImgView.image=[UIImage imageNamed:@"white_arrow"];
    }
    
}

-(void)hideDevicesListView{
    [UIView animateWithDuration:0.2 animations:^{
        CGRect rect = devicesTableView.frame;
        rect.size.height = 0;
        devicesTableView.frame=rect;
    } completion:^(BOOL finished) {
        devicesTableView.delegate=nil;
        devicesTableView.dataSource=nil;
        [devicesTableView removeFromSuperview];
        devicesTableView=nil;
        
        [devicesListCoverView removeFromSuperview];
        devicesListCoverView=nil;
    }];
}

-(void)showHideDevicesListView{
    
    //show
    if (!devicesListCoverView) {
        [self addDevicesListView];
        
        [UIView animateWithDuration:0.2 animations:^{
            CGRect rect = devicesTableView.frame;
            rect.size.height = devicesListCoverView.frame.size.height-landscapeTopView.frame.size.height;
            devicesTableView.frame=rect;
            
        }completion:^(BOOL finished) {
        }];
    }else{
        //dismiss
        [self hideDevicesListView];
    }
    
}

-(void)handlePanGestureChangeStream:(UIGestureRecognizer *)gestureRecognizer{
    
    float initialPointX = 0.0;
    float changedPointX = 0.0;
    
    CGPoint location = [gestureRecognizer locationInView:self.view];
    
    //    if ([self currentScreenLandscape]) {
    //
    //        initialPointX = formerPoint.y;
    //        changedPointX = location.y;
    //
    //    }else{
    initialPointX = formerPoint.x;
    changedPointX = location.x;
    //    }
    
    //    NSLog(@"initialPointX = %.2f changedPointX =%.2f",initialPointX,changedPointX);
    
    UIView *tagetView=nil;
    CGFloat targetX = 0.0;
    
    if(gestureRecognizer.state == UIGestureRecognizerStateChanged){
        //向右滑动
        if(changedPointX  - initialPointX < 0)
        {
            //到头了
            if (self.currentDeviceIndex==self.devicesArray.count-1) {
                return;
            }
            
            tagetView = rightLoadingFakeView;
            targetX= rightLoadingFakeOriginalX;
            
        }
        //向左滑动
        if(changedPointX  - initialPointX > 0)
        {
            //第一个
            if (self.currentDeviceIndex==0) {
                return;
            }
            
            tagetView = leftLoadingFakeView;
            targetX= leftLoadingFakeOriginalX;
        }
        
        CGRect _rec = openglview.frame;
        _rec.origin.x = changedPointX  - initialPointX;
        _rec.origin.y=0;
        openglview.frame = _rec;
        
        _rec = tagetView.frame;
        _rec.origin.x = targetX + (changedPointX  - initialPointX);
        _rec.origin.y=0;
        tagetView.frame = _rec;
        
        if(waitview){
            static CGFloat waitViewFrameX=waitview.frame.origin.x;
            
            _rec = waitview.frame;
            _rec.origin.x = waitViewFrameX + changedPointX  - initialPointX;
            waitview.frame=_rec;
        }
        
        if(errorview){
            static CGFloat errorViewFrameX=errorview.frame.origin.x;
            
            _rec = errorview.frame;
            _rec.origin.x = errorViewFrameX + changedPointX  - initialPointX;
            errorview.frame=_rec;
        }
        
        
    }else if(gestureRecognizer.state >= UIGestureRecognizerStateEnded){
        //        CGPoint location = [gestureRecognizer locationInView:self.view];
        NSTimeInterval time = 0.2;
        
        //向左滑
        if(changedPointX  - initialPointX < 0){
            //到头了
            if (self.currentDeviceIndex==self.devicesArray.count-1) {
                return;
            }
            
            //向左滑动超过50
            if(changedPointX  - initialPointX < -50){
                if (pauseBtn.selected) {
                    [self clickPause];
                }
                [UIView animateWithDuration:time animations:^{
                    CGRect _rec = openglview.frame;
                    _rec.origin.x = -openglview.frame.size.width;
                    openglview.frame = _rec;
                    
                    _rec = rightLoadingFakeView.frame;
                    _rec.origin.x = 0;
                    rightLoadingFakeView.frame = _rec;
                    
                    
                    if(waitview){
                        
                        CGPoint point = waitview.center;
                        point.x = -openglview.frame.size.width/2;
                        waitview.center=point;
                    }
                    
                    if(errorview){
                        
                        //                        _rec = errorview.frame;
                        //                        _rec.origin.x =-openglview.frame.size.width/2;
                        //                        errorview.frame=_rec;
                        
                        CGPoint point = errorview.center;
                        point.x = -openglview.frame.size.width/2;
                        errorview.center=point;
                    }
                    
                } completion:^(BOOL finished) {
                    //                        return;
                    //到头了
                    if (self.currentDeviceIndex==self.devicesArray.count-1) {
                        return;
                    }
                    
                    //还原
                    CGRect _rec = openglview.frame;
                    _rec.origin.x = 0;
                    openglview.frame = _rec;
                    
                    _rec = rightLoadingFakeView.frame;
                    _rec.origin.x = openglview.frame.size.width;
                    rightLoadingFakeView.frame = _rec;
                    
                    //                    [self quicklyStopMovie];
                    self.currentDeviceIndex++;
                    if(self.currentDeviceIndex<self.devicesArray.count && self.currentDeviceIndex>=0){
                        [self changeStream:[self.devicesArray objectAtIndex:self.currentDeviceIndex]];
                        
                    }
                    
                    
                }];
            }
            //向左滑动不超过50
            else{
                [UIView animateWithDuration:time animations:^{
                    CGRect _rec = openglview.frame;
                    _rec.origin.x = 0;
                    openglview.frame = _rec;
                    
                    _rec = rightLoadingFakeView.frame;
                    _rec.origin.x = openglview.frame.size.width;
                    rightLoadingFakeView.frame = _rec;
                    
                    if(waitview){
                        
                        //                        _rec = waitview.frame;
                        //                        _rec.origin.x =openglview.frame.size.width/2;
                        //                        waitview.frame=_rec;
                        
                        
                        CGPoint point = waitview.center;
                        point.x = openglview.frame.size.width/2;
                        waitview.center=point;
                    }
                    
                    if(errorview){
                        
                        //                        _rec = errorview.frame;
                        //                        _rec.origin.x =openglview.frame.size.width/2;
                        //                        errorview.frame=_rec;
                        CGPoint point = errorview.center;
                        point.x = openglview.frame.size.width/2;
                        errorview.center=point;
                    }
                    
                } completion:^(BOOL finished) {
                }];
                
            }
            
            
        }
        
        
        //滑到右边
        if(changedPointX  - initialPointX > 0){
            if (self.currentDeviceIndex==0) {
                return ;
            }
            //向右滑动超过50
            if(changedPointX  - initialPointX > 50){
                
                if (pauseBtn.selected) {
                    [self clickPause];
                }
                //                NSTimeInterval time = fabs(openglview.frame.origin.x - openglview.frame.size.width) *0.01 ;
                [UIView animateWithDuration:time animations:^{
                    
                    
                    CGRect _rec = openglview.frame;
                    _rec.origin.x = openglview.frame.size.width;
                    openglview.frame = _rec;
                    
                    _rec = leftLoadingFakeView.frame;
                    _rec.origin.x = 0;
                    leftLoadingFakeView.frame = _rec;
                    
                    
                    if(waitview){
                        
                        CGPoint point = waitview.center;
                        point.x =openglview.frame.size.width + openglview.frame.size.width/2;
                        waitview.center=point;
                        //                        _rec = waitview.frame;
                        //                        _rec.origin.x =openglview.frame.size.width +openglview.frame.size.width/2;
                        //                        waitview.frame=_rec;
                    }
                    
                    if(errorview){
                        
                        CGPoint point = errorview.center;
                        point.x =openglview.frame.size.width + openglview.frame.size.width/2;
                        errorview.center=point;
                    }
                    
                } completion:^(BOOL finished) {
                    if (self.currentDeviceIndex==0) {
                        return ;
                    }
                    
                    CGRect _rec = openglview.frame;
                    _rec.origin.x = 0;
                    openglview.frame = _rec;
                    
                    _rec = leftLoadingFakeView.frame;
                    _rec.origin.x = -openglview.frame.size.width;
                    leftLoadingFakeView.frame = _rec;
                    
                    self.currentDeviceIndex--;
                    if(self.currentDeviceIndex<self.devicesArray.count && self.currentDeviceIndex>=0){
                        [self changeStream:[self.devicesArray objectAtIndex:self.currentDeviceIndex]];
                    }
                    
                    
                }];
            }
            // 向右滑动不超过50
            
            else{
                [UIView animateWithDuration:time animations:^{
                    CGRect _rec = openglview.frame;
                    _rec.origin.x = 0;
                    openglview.frame = _rec;
                    
                    _rec = leftLoadingFakeView.frame;
                    _rec.origin.x = -openglview.frame.size.width;
                    leftLoadingFakeView.frame = _rec;
                    
                    
                    if(waitview){
                        //                        _rec = waitview.frame;
                        //                        _rec.origin.x =openglview.frame.size.width/2;
                        //                        waitview.frame=_rec;
                        
                        CGPoint point = waitview.center;
                        point.x =openglview.frame.size.width/2;
                        waitview.center=point;
                    }
                    
                    if(errorview){
                        
                        CGPoint point = errorview.center;
                        point.x =openglview.frame.size.width/2;
                        errorview.center=point;
                    }
                    
                } completion:^(BOOL finished) {
                }];
                
            }
            
        }
        
    }
    
    
    
    
    
}


#pragma mark -

-(void)saveCaptureImageToAiweiAlbum:(UIImage *)image{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //首先创建aiweibaby相册，ios8下存在相册删除后无法重新创建的bug
        [self createAlbumInPhoneAlbum:^(BOOL existed) {
            NSLog(@"albumExisted %d",existed);
            
            NSData *imageData = UIImageJPEGRepresentation(image, 1);
            [self saveToAlbumWithMetadata:nil imageData:imageData customAlbumName:existed?ALBUMNAME:nil completionBlock:^{
                NSLog(@"save ok");
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    MBProgressHUD *ahud=[MBProgressHUD showHUDAddedTo:self.view animated:YES];
                    ahud.userInteractionEnabled = NO;
                    ahud.mode = MBProgressHUDModeText;
                    ahud.labelText = [NSString stringWithFormat:@"已保存到%@相册", existed?ALBUMNAME:@""];
                    ;
                    [ahud hide:YES afterDelay:0.5];
                    
                    //模拟动画
                    CGRect rc = [self.view convertRect:openglview.frame fromView:carrierView];
                    
                    __block UIImageView*captureImgView = [[UIImageView alloc]initWithFrame:rc];
                    [self.view addSubview:captureImgView];
                    captureImgView.image=image;
                    
                    [UIView animateWithDuration:0.5 animations:^{
                        CGRect rect=captureImgView.frame;
                        
                        rect.origin.x=self.view.frame.size.width;
                        rect.size.width=1;
                        rect.size.height=1;
                        rect.origin.y=self.view.frame.size.height;
                        captureImgView.frame=rect;
                        
                    } completion:^(BOOL finished) {
                        [captureImgView removeFromSuperview];
                        captureImgView=nil;
                    }];
                    
                });
                
            } failureBlock:^(NSError *error) {
                NSLog(@"save failureBlock");
                
            }];
            
        }];
    });
}
#pragma mark 在手机相册中创建相册
- (void)createAlbumInPhoneAlbum:(void (^)(BOOL albumExisted))resultBlock
{
    if (!assetsLibrary) {
        assetsLibrary = [[ALAssetsLibrary alloc] init];
    }
    NSMutableArray *groups=[[NSMutableArray alloc]init];
    ALAssetsLibraryGroupsEnumerationResultsBlock listGroupBlock = ^(ALAssetsGroup *group, BOOL *stop)
    {
        if (group)
        {
            [groups addObject:group];
        }
        
        else
        {
            BOOL haveAiweiGroup = NO;
            
            for (ALAssetsGroup *gp in groups)
            {
                NSString *name =[gp valueForProperty:ALAssetsGroupPropertyName];
                
                if ([name isEqualToString:ALBUMNAME])
                {
                    haveAiweiGroup = YES;
                    resultBlock(haveAiweiGroup);
                }
            }
            
            if (!haveAiweiGroup)
            {
                [assetsLibrary addAssetsGroupAlbumWithName:ALBUMNAME
                                               resultBlock:^(ALAssetsGroup *group){
                                                   if(group){
                                                       [groups addObject:group];
                                                       resultBlock(YES);
                                                   }else{
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_8_0
                                                       
                                                       //处理ios8下的相册删除后无法重建问题
                                                       [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
                                                           [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:ALBUMNAME];
                                                           
                                                       } completionHandler:^(BOOL success, NSError *error) {
                                                           resultBlock(success);
                                                       }];
                                                       
#else
                                                       resultBlock(success);
#endif
                                                   }
                                               }
                                              failureBlock:^(NSError *error) {
                                                  NSLog(@"error=%@", error);
                                                  resultBlock(NO);
                                                  
                                                  
                                              }];
            }
        }
        
    };
    //创建相簿
    [assetsLibrary enumerateGroupsWithTypes:ALAssetsGroupAlbum usingBlock:listGroupBlock failureBlock:^(NSError *error) {
        resultBlock(NO);
    }];
    
    
}

#pragma mark 保存照片到相册

- (void)saveToAlbumWithMetadata:(NSDictionary *)metadata
                      imageData:(NSData *)imageData
                customAlbumName:(NSString *)customAlbumName
                completionBlock:(void (^)(void))completionBlock
                   failureBlock:(void (^)(NSError *error))failureBlock
{
    
    __weak typeof(assetsLibrary) weakAssetsLibrary = assetsLibrary;
    
    /*
     void (^AddAsset)(ALAssetsLibrary *, NSURL *) = ^(ALAssetsLibrary *_assetsLibrary, NSURL *assetURL) {
     NSLog(@"assetURL = %@", assetURL);
     
     __block BOOL hasAddedToAsset=NO;
     
     [_assetsLibrary assetForURL:assetURL resultBlock:^(ALAsset *asset) {
     [_assetsLibrary enumerateGroupsWithTypes:ALAssetsGroupAll
     usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
     
     // add image to aiwebaby asset
     if ([[group valueForProperty:ALAssetsGroupPropertyName] isEqualToString:customAlbumName]) {
     hasAddedToAsset=YES;
     [group addAsset:asset];
     if (completionBlock) {
     NSLog(@"/ add image to aiwebaby asset");
     completionBlock();
     }
     }
     
     if(!hasAddedToAsset && group==nil){
     if (completionBlock) {
     NSLog(@"/ add image to sys asset");
     completionBlock();
     }
     }
     
     } failureBlock:^(NSError *error) {
     if (failureBlock) {
     NSLog(@"/ failureBlock");
     failureBlock(error);
     }
     }];
     } failureBlock:^(NSError *error) {
     if (failureBlock) {
     NSLog(@"/ failureBlock");
     failureBlock(error);
     }
     }];
     };
     */
    
    //add to system album
    [assetsLibrary writeImageDataToSavedPhotosAlbum:imageData metadata:metadata completionBlock:^(NSURL *assetURL, NSError *error) {
        NSLog(@"writeImageDataToSavedPhotosAlbum completionBlock");
        
        if(!customAlbumName){
            if (completionBlock) {
                completionBlock();
            }
            return ;
        }
        
        __block BOOL albumWasFound = NO;
        
        [weakAssetsLibrary enumerateGroupsWithTypes:ALAssetsGroupAlbum usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
            //find album
            if ([customAlbumName compare: [group valueForProperty:ALAssetsGroupPropertyName]]==NSOrderedSame) {
                albumWasFound = YES;
                //find img asset
                [weakAssetsLibrary assetForURL: assetURL
                                   resultBlock:^(ALAsset *asset) {
                                       //add img to aiwei
                                       if([group addAsset: asset]){
                                           if (completionBlock) {
                                               completionBlock();
                                           }
                                       }
                                   }
                                  failureBlock:^(NSError *error) {
                                      if (completionBlock) {
                                          completionBlock();
                                      }
                                  }
                 ];
                
                
            }
            
            //no aiwei
            if (group==nil && albumWasFound==NO) {
                if (completionBlock) {
                    completionBlock();
                }
            }
            
            
        }
                                       failureBlock:^(NSError *error) {
                                           if (completionBlock) {
                                               completionBlock();
                                           }
                                       }];
        /*
         [weakAssetsLibrary addAssetsGroupAlbumWithName:customAlbumName resultBlock:^(ALAssetsGroup *group) {
         NSLog(@"addAssetsGroupAlbumWithName resultBlock");
         
         if (group) {
         
         //find image url
         [weakAssetsLibrary assetForURL:assetURL resultBlock:^(ALAsset *asset) {
         
         //add to aiwei album
         if ([group addAsset:asset]) {
         
         //del image in system album
         [asset setImageData:NULL metadata:NULL completionBlock:^(NSURL *assetURL, NSError *error)
         {
         }];
         };
         
         
         if (completionBlock) {
         completionBlock();
         }
         } failureBlock:^(NSError *error) {
         if (failureBlock) {
         failureBlock(error);
         }
         }];
         } else {
         AddAsset(weakAssetsLibrary, assetURL);
         }
         } failureBlock:^(NSError *error) {
         NSLog(@"addAssetsGroupAlbumWithName failureBlock");
         AddAsset(weakAssetsLibrary, assetURL);
         }];
         */
    }];
}

#pragma mark -
-(void)showHidePlotView{
    NSLog(@"longPress");
    
    //没有,弹出
    if(!plotCoverView){
        plotCoverView = [[UIView alloc]initWithFrame:CGRectMake(self.view.frame.size.width, carrierView.frame.size.height, self.view.frame.size.width, self.view.frame.size.height - carrierView.frame.size.height)];
        
        [self.view addSubview:plotCoverView];
        
        //初始化图表
        [self initLineGraph];
        //加载图表数据
//        [self loadPlotsData];
        
        [self loadPlotTip];
        
        [UIView animateWithDuration:0.2 animations:^{
            CGRect rect = plotCoverView.frame;
            rect.origin.x=0;
            plotCoverView.frame=rect;
        } completion:^(BOOL finished) {
            
        }];
    }
    //有,消失
    else{
        [UIView animateWithDuration:0.2 animations:^{
            CGRect rect = plotCoverView.frame;
            rect.origin.x=self.view.frame.size.width;
            plotCoverView.frame=rect;
        } completion:^(BOOL finished) {
            [plotCoverView removeFromSuperview];
            plotCoverView = nil;
        }];
    }
    
}

-(void)initLineGraph{
    
}

-(NSArray *)producePlotValues:(NSArray *)plotValues{
    if (plotValues.count==0) {
        return @[ @{ @1 : @0.0 }, @{ @2 : @0.0 }, @{ @3 : @0.0 },
                  @{ @4 : @0.0 }, @{ @5 : @0.0 }, @{ @6 : @0.0 },
                  @{ @7 : @0.0 }, @{ @8 : @0.0 }, @{ @9 : @0.0 },
                  @{ @10 : @0.0 },@{ @11 : @0.0}, @{ @12 : @0.0 }
                  ];
    }
    
    
    NSMutableArray *temp=[NSMutableArray array];
    for (int i=0; i<plotValues.count;i++) {
        
        NSDictionary *dic = @{[NSNumber numberWithInt:i+1]:
                                  plotValues[i]};
        temp[i]=dic;
    }
    
    return temp;
    
    
}


 /**
 *  refreshPlots
 *
 *  刷新即时分析图表
 */

-(void)refreshPlots{
    
//    [_lineGraph removeFromSuperview];
//    _lineGraph=nil;
    
    [self initLineGraph];
//    [self loadPlotsData];
}

-(void)loadPlotTip{
    // Do any additional setup after loading the view.
    UIView *view = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, plotCoverView.frame.size.width, 30)];
    [plotCoverView addSubview:view];
    [view setBackgroundColor:[UIColor whiteColor]];
    
    //加载指示
    float viewwidth = 20;
    float labelwidth = 40;
    
    float view1OriginalX = (view.frame.size.width - (viewwidth + labelwidth)*2)/2;
    
    UIView *view1 = [[UILabel alloc] initWithFrame:CGRectMake(view1OriginalX, 10, viewwidth, 1)];
    view1.backgroundColor = VIDEOSOURCE_COLOR;
    [plotCoverView addSubview:view1];
    
    UILabel *label1 = [[UILabel alloc] initWithFrame:CGRectMake(view1.frame.origin.x + view1.frame.size.width, 2, labelwidth, 18)];
    label1.backgroundColor = [UIColor clearColor];
    label1.textColor = VIDEOSOURCE_COLOR;
    label1.textAlignment=NSTextAlignmentCenter;
    label1.font = [UIFont systemFontOfSize:9];
    [plotCoverView addSubview:label1];
    label1.text=@"视频源";
    
    
    UIView *view2 = [[UILabel alloc] initWithFrame:CGRectMake(label1.frame.origin.x + label1.frame.size.width, 10, viewwidth, 1)];
    view2.backgroundColor = CLIENTSOURCE_COLOR;
    [plotCoverView addSubview:view2];
    
    UILabel *label2 = [[UILabel alloc] initWithFrame:CGRectMake(view2.frame.origin.x + view2.frame.size.width, 2, labelwidth, 18)];
    label2.backgroundColor = [UIColor clearColor];
    label2.textColor = CLIENTSOURCE_COLOR;
    label2.font = [UIFont systemFontOfSize:9];
    [plotCoverView addSubview:label2];
    label2.textAlignment=NSTextAlignmentCenter;
    
    label2.text=@"手机端";
    
}

-(void)releaseGraphView{
    
//    [_lineGraph removeFromSuperview];
//    _lineGraph=nil;
//    
    [plotCoverView removeFromSuperview];
    plotCoverView=nil;
    
}

#pragma mark  - Autorotate

- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    //    DLog();
    
    //手动旋转
    id switch_landscape = [[NSUserDefaults standardUserDefaults] objectForKey:KSWITCH_LANDSCAPE];
    
    
    if (!transformManu && switch_landscape == nil) {
        NSLog(@"不是手动旋转，而且选项里禁方向。那么屏幕旋转时禁止旋转");
        //返回当前位置
        if([self currentScreenLandscape]){
            return  UIInterfaceOrientationLandscapeRight;
        }
        return  UIInterfaceOrientationMaskPortrait;
        
    }
    
    
    //其他
    
    //    //是否允许横屏
    //    if([[NSUserDefaults standardUserDefaults] objectForKey:KSWITCH_LANDSCAPE])
    //    {
    return  UIInterfaceOrientationMaskAllButUpsideDown;
    
    //    }else{
    //        return  UIInterfaceOrientationMaskPortrait;
    //    }
    //    
}

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
    
    DLog();
    
    UIInterfaceOrientation wantInterfaceOrientation = toInterfaceOrientation;
    //
    ////    //禁止旋转
    //    id switch_landscape = [[NSUserDefaults standardUserDefaults] objectForKey:KSWITCH_LANDSCAPE];
    //    if (!transformManu && switch_landscape == nil)
    //    {
    //        NSLog(@" willRotateToInterfaceOrientation不是手动旋转，而且选项里禁方向。那么屏幕旋转时禁止旋转");
    ////        return;
    //        if([self currentScreenLandscape]){
    //            wantInterfaceOrientation =  UIInterfaceOrientationLandscapeRight;
    //        }else{
    //            wantInterfaceOrientation = UIInterfaceOrientationPortrait;
    //        }
    //     }
    
    //    return;
    //
    //    if([[NSUserDefaults standardUserDefaults] objectForKey:KSWITCH_LANDSCAPE]){
    
    //        transformManu=NO;
    [self rotateView:wantInterfaceOrientation];
    transformManu = NO;
    
    //    }
}



@end
